
package org.example.domain.service.config;

import jakarta.annotation.PostConstruct;
import org.springdoc.core.properties.AbstractSwaggerUiConfigProperties;
import org.springdoc.core.properties.SwaggerUiConfigProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import static org.springdoc.core.utils.Constants.SPRINGDOC_ENABLED;

/**
 * 本地访问swagger配置
 */

@Configuration
@ConditionalOnProperty(name = SPRINGDOC_ENABLED, matchIfMissing = true)
public class SpringdocConfig {
    protected final SwaggerUiConfigProperties swaggerUiConfigProperties;
    protected final RouteDefinitionLocator routeDefinitionLocator;

    public SpringdocConfig(SwaggerUiConfigProperties swaggerUiConfigProperties, RouteDefinitionLocator routeDefinitionLocator) {
        this.swaggerUiConfigProperties = swaggerUiConfigProperties;
        this.routeDefinitionLocator = routeDefinitionLocator;
    }

    @PostConstruct
    public void autoInitSwaggerUrls() {
        List<RouteDefinition> definitions = routeDefinitionLocator.getRouteDefinitions().collectList().block();
        if (definitions != null && !definitions.isEmpty()) {
            definitions.forEach(routeDefinition -> {
                AbstractSwaggerUiConfigProperties.SwaggerUrl swaggerUrl = new AbstractSwaggerUiConfigProperties.SwaggerUrl(
                        routeDefinition.getId().replace("ReactiveCompositeDiscoveryClient_", "").toLowerCase(),
                        routeDefinition.getUri().toString().replace("lb://", "").toLowerCase() + "/v3/api-docs",
                        routeDefinition.getId().replace("ReactiveCompositeDiscoveryClient_", "").toLowerCase()
                );
                Set<AbstractSwaggerUiConfigProperties.SwaggerUrl> urls = swaggerUiConfigProperties.getUrls();
                if (urls == null) {
                    urls = new LinkedHashSet<>();
                    swaggerUiConfigProperties.setUrls(urls);
                }
                urls.add(swaggerUrl);
            });
        }
    }
}